<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<title>应急信息发布区域管理地图</title>
	<style type="text/css">
		body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
		#result {width:100%;font-size:12px;}
		
		ul,li{list-style: none;margin:0;padding:0;float:left;}
		#container{height:100%;width:100%;}
		#r-result{width:100%;} 
	</style>
	<!-- <link href="../../layui/css/layui.css" rel="stylesheet" type="text/css"> 
	<script src="../../layui/layui.js"></script>
	<link href="../../css/style.css" rel="stylesheet" type="text/css">
	<script src="../../js/jquery-1.8.3.js"></script> -->
	<script src="../../layui/layui.js"></script>
	<script src="../../js/util.js"></script>
	<link rel="stylesheet" type="text/css" href="../../css/mapstyle.css">
	<link rel="stylesheet" type="text/css" href="../../css/xcConfirm.css"/>
	<script src="../../js/jquery-1.9.1.js" type="text/javascript" charset="utf-8"></script>
	<script src="../../js/xcConfirm.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=nSGoPNzNrehEaGBst1TZzklH"></script>
	<!--加载鼠标绘制工具-->
	<script type="text/javascript" src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
	<link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
	<!--加载检索信息窗口-->
	<script type="text/javascript" src="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.js"></script>
	<link rel="stylesheet" href="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.css" />
	<!--测算工具类-->
	<script type="text/javascript" src="http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js"></script>
	<!-- <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=nSGoPNzNrehEaGBst1TZzklH"></script> -->
    <script type="text/javascript" src="http://api.map.baidu.com/library/Heatmap/2.0/src/Heatmap_min.js"></script>
	
</head>
<body>
	<div id="allmap"></div>
	<div id="loadingDiv" class="load-white-bg hide">
	<span class="qloading">正在加载...</span>
	</div> 
	<!-- <input type="button" value="获取绘制的覆盖物个数" onclick="alert(overlays.length)"/>
	<input type="button" value="清除所有覆盖物" onclick="clearAll()"/>
	<input type="button" value="保存" onclick="onSave()"/> -->
</body>
</html>
<script type="text/javascript">
layui.use(['table', 'form', 'jquery', 'element','layer','laydate'], function () {
var map = null;
var layer=layui.layer;
var resultStation=[];//基站结果
	//基站数量
var stationCount;
var	regionId;
var resultPoint=[];//结果点位
var resultRegionValue;//结果区域图形值 1: a,b   2:经度，纬度#半径   3:4: 经度，纬度#经度，纬度
var resultRegionType;//结果区域图形 1行政区域组合 2圆形 3矩形 4 多边形
var reliPoints = [];//热力图经纬度及人流量
var overlays = [];
var flagheatmap = "0";//热力图开关标识 1:热力图打开   0.热力图关闭
var initialFunc = function(){
    // 百度地图API功能
	map = new BMap.Map("allmap",{enableMapClick:false},{minZoom:5,maxZoom:18}); // 创建Map实例,设置地图允许的最小/大级别
	if(isHaveJW!=""){
		map.centerAndZoom(isHaveJW,13); // 初始化地图,设置中心点坐标和地图级别
	}else{
		map.centerAndZoom(cityJW,13); // 初始化地图,设置中心点坐标和地图级别
		map.centerAndZoom(regionName,13); // 初始化地图,设置中心点坐标和地图级别
	}
	
	var top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});// 左上角，添加比例尺
	var top_left_navigation = new BMap.NavigationControl();  //左上角，添加默认缩放平移控件
	//单击获取点击的经纬度
   /*  map.addEventListener("click",function(e){
        //alert(e.point.lng + "," + e.point.lat);
    }); */
	map.enableScrollWheelZoom(true);//开启鼠标滚轮缩放 
	map.addEventListener("dragend", function showInfo(){
	   if(flagheatmap=='1'){
	   	 map.removeOverlay(heatmapOverlay);
	   }
	   getHeatMap();
	});
	map.addEventListener("zoomend", function showInfo(){
	   if(flagheatmap=='1'){
	   	 map.removeOverlay(heatmapOverlay);
	   }
	   if(map.getZoom()<heatMapLimit){
	   	 map.addControl(myHeatmapOpenCtrl);
		 map.removeControl(myHeatmapCloseCtrl);	
	   }
	   getHeatMap();
	});
	//热力图
	//getHeatMap();
	//热力图
	
	/* 创建比例尺工具 */
	map.addControl(top_left_control); 
	/* 添加默认缩放平移控件 */
	map.addControl(top_left_navigation);   // 左导航默认  
	
	/*创建保存按钮*/
	// 定义一个控件类,即function
	function ZoomControl(){
	    // 默认停靠位置和偏移量
	    this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
	    this.defaultOffset = new BMap.Size(10, 10); // 距离左上角位置
	}
	
	// 通过JavaScript的prototype属性继承于BMap.Control
	ZoomControl.prototype = new BMap.Control();
	
	// 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
	// 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
	ZoomControl.prototype.initialize = function(map){
		// 创建一个DOM元素
		var div = document.createElement("div");
		// 添加文字说明
		div.appendChild(document.createTextNode("保存"));
		// 设置样式
		div.style.cursor = "pointer";
		div.style.border = "1px solid gray";
		div.style.backgroundColor = "white";
		div.style.width = "30px";
		div.style.height = "45px";
		div.style.textAlign='center';
		div.style.backgroundColor='#2e84b5';
		div.style.color='#ededed';
		// 绑定事件,点击一次放大两级
		div.onclick = function(e){
			if(overlays.length>1){
			    window.wxc.xcConfirm("当前覆盖物为"+overlays.length+"个，请清除后，重新选取发送区域进行保存", window.wxc.xcConfirm.typeEnum.info);
			}else if(overlays.length==0){
				window.wxc.xcConfirm("请先选取发送区域再进行保存", window.wxc.xcConfirm.typeEnum.info);
			}else{
				//alert(resultPoint.length);
				/* layer.confirm('此操作将保存发送范围，请确认', {
                    btn: ['确认提交', '再看看']
                }, function () {
                	reset = 0;
                	mapSave();
                }, function() {
    				reset = 0;
                }) */
                var txt=  "此操作将保存发送范围，请确认！";
						var option = {
							title: "提示",
							btn: parseInt("0011",2),//0001确认按钮     0011 确认取消
							onOk: function(){
								mapSave();
							}
						}
						window.wxc.xcConfirm(txt, "custom", option);
			}
		} 
		// 添加DOM元素到地图中
		map.getContainer().appendChild(div);
		// 将DOM元素返回
		return div;
	}
	// 创建控件
	var myZoomCtrl = new ZoomControl();
	// 添加到地图当中
	map.addControl(myZoomCtrl);
	
	/*创建提示语句*/
	function msgControl(){
	    // 默认停靠位置和偏移量
	    this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
	    this.defaultOffset = new BMap.Size(245, 10); // 距离左上角位置
	}
	msgControl.prototype = new BMap.Control();
	msgControl.prototype.initialize = function(map){
		var div = document.createElement("div");
		div.appendChild(document.createTextNode("1.圈画多边形时最后收尾需双击鼠标2.地图缩放到一定级别不展示热力图"));
		div.style.border = "1px solid gray";
		div.style.backgroundColor = "white";
		div.style.width = "260px";
		div.style.height = "40px";
		//div.style.textAlign='center';
		div.style.borderRadius='5px';
		div.style.backgroundColor='#2e84b5';
		div.style.color='#ededed';
		div.onclick = function(e){
		} 
		map.getContainer().appendChild(div);
		return div;
	}
	var myMsgCtrl = new msgControl();
	map.addControl(myMsgCtrl);
	
	/*创建提示语句关闭按钮*/
	function msgCloseControl(){
	    // 默认停靠位置和偏移量
	    this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
	    this.defaultOffset = new BMap.Size(505, 10); // 距离左上角位置
	}
	msgCloseControl.prototype = new BMap.Control();
	msgCloseControl.prototype.initialize = function(map){
		var div = document.createElement("div");
		div.appendChild(document.createTextNode("X"));
		div.style.cursor = "pointer";
		div.style.border = "1px solid gray";
		div.style.backgroundColor = "white";
		div.style.width = "20px";
		div.style.height = "20px";
		div.style.textAlign='center';
		div.style.borderRadius='5px';
		div.style.backgroundColor='#2e84b5';
		div.style.color='#ededed';
		//div.backgroundImage='../../images/iw_close1d3.gif';
		div.onclick = function(e){
		    map.removeControl(myMsgCtrl);
		    map.removeControl(myMsgCloseCtrl);
		} 
		map.getContainer().appendChild(div);
		return div;
	}
	var myMsgCloseCtrl = new msgCloseControl();
	map.addControl(myMsgCloseCtrl);
	
	/*创建清除按钮*/
	function clearControl(){
	    // 默认停靠位置和偏移量
	    this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
	    this.defaultOffset = new BMap.Size(45, 10); // 距离左上角位置
	}
	clearControl.prototype = new BMap.Control();
	clearControl.prototype.initialize = function(map){
		var div = document.createElement("div");
		div.appendChild(document.createTextNode("清除"));
		div.style.cursor = "pointer";
		div.style.border = "1px solid gray";
		div.style.backgroundColor = "white";
		div.style.width = "30px";
		div.style.height = "45px";
		div.style.textAlign='center';
		div.style.backgroundColor='#2e84b5';
		div.style.color='#ededed';
		div.onclick = function(e){
		    clearAll();
		} 
		map.getContainer().appendChild(div);
		return div;
	}
	var myClearCtrl = new clearControl();
	map.addControl(myClearCtrl);
	/*创建清除按钮end*/
	
	/*创建热力图关闭按钮*/
	function heatmapCloseControl(){
	    // 默认停靠位置和偏移量
	    this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
	    /* this.defaultOffset = new BMap.Size(10, 60); // 距离左上角位置 */
	    this.defaultOffset = new BMap.Size(380, 10); // 距离左上角位置
	}
	heatmapCloseControl.prototype = new BMap.Control();
	heatmapCloseControl.prototype.initialize = function(map){
		var div = document.createElement("div");
		div.appendChild(document.createTextNode("关闭热力图"));
		div.style.cursor = "pointer";
		div.style.border = "1px solid gray";
		div.style.backgroundColor = "white";
		div.style.width = "60px";
		div.style.height = "45px";
		div.style.textAlign='center';
		div.style.backgroundColor='#2e84b5';
		div.style.color='#ededed';
		div.onclick = function(e){
				if(map.getZoom()>(heatMapLimit-1)){
					OpenOrCloseHeatmap();//开启或关闭热力图
					map.addControl(myHeatmapOpenCtrl);
					map.removeControl(myHeatmapCloseCtrl);
				}else{
					layer.msg("地图范围过大，热力图默认关闭");
				}
			}
		map.getContainer().appendChild(div);
		return div;
	}
	var myHeatmapCloseCtrl = new heatmapCloseControl();
	//map.addControl(myHeatmapCloseCtrl);
	/*创建热力图关闭按钮end*/
	
	/*创建热力图开启按钮*/
	function heatmapOpenControl(){
	    // 默认停靠位置和偏移量
	    this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
	    this.defaultOffset = new BMap.Size(380, 10); // 距离左上角位置
	}
	heatmapOpenControl.prototype = new BMap.Control();
	heatmapOpenControl.prototype.initialize = function(map){
		var div = document.createElement("div");
		div.appendChild(document.createTextNode("开启热力图"));
		div.style.cursor = "pointer";
		div.style.border = "1px solid gray";
		div.style.backgroundColor = "white";
		div.style.width = "60px";
		div.style.height = "45px";
		div.style.textAlign='center';
		div.style.backgroundColor='grey';
		div.style.color='#ededed';
		div.onclick = function(e){
				if(map.getZoom()>(heatMapLimit-1)){
					OpenOrCloseHeatmap();//开启或关闭热力图
					map.addControl(myHeatmapCloseCtrl);
					map.removeControl(myHeatmapOpenCtrl);
				}else{
					layer.msg("地图范围过大，热力图默认关闭");
				}
			}
		map.getContainer().appendChild(div);
		return div;
	}
	var myHeatmapOpenCtrl = new heatmapOpenControl();
	map.addControl(myHeatmapOpenCtrl);
	/*创建热力图关闭按钮end*/
	var overlaycomplete = function(e){
		
	    overlays.push(e.overlay);
	    //圆
	    if (e.drawingMode == BMAP_DRAWING_CIRCLE) {  
	        resultRegionType="2";
	        resultRegionValue="";//清空
	        var c = new BMap.Point(e.overlay.getCenter().lng, e.overlay.getCenter().lat); 
	        var radius=e.overlay.getRadius();
	        resultRegionValue=e.overlay.getCenter().lng+","+e.overlay.getCenter().lat+"+"+radius;
	       /*  resultPoint=[];//清空
	        resultStation=[];
	        for(var index = 0; index < markers.length; index++ ){
	            var pt = new BMap.Point(markers[index].position.lng,markers[index].position.lat);
	            if(ptInCircle(pt,c,radius)){
	                var object = new Object();
	                object.lnglatX = markers[index].position.lng;
	                object.lnglatY = markers[index].position.lat;
	                resultPoint.push(object);
	                var object2 = new Object();
	                object2.stationid=markers[index].stationid;
	                object2.stationname=markers[index].stationname;
	                resultStation.push(object2);
	            }
	        } */
	    }  
	    //矩形
	    if(e.drawingMode == BMAP_DRAWING_RECTANGLE){
	        resultRegionType="3";
	        var jdwdArr=[];
	        resultRegionValue="";//清空
	        for(var i = 0; i < e.overlay.getPath().length; i++){
	             var object = new Object();
	             object.X= e.overlay.getPath()[i].lng;
	             object.Y= e.overlay.getPath()[i].lat;
	             jdwdArr.push(object);
	             resultRegionValue +=object.X+","+object.Y+"+";
	        }
	        /* resultRegionValue="";//清空
	        var resultJD=[];//经度
	        var resultWD=[];//维度
	        for(var i = 0; i < e.overlay.getPath().length; i++){
	           var jd= e.overlay.getPath()[i].lng;
	           resultJD.push(jd);
	           var wd= e.overlay.getPath()[i].lat;
	           resultWD.push(wd);
	        }
	        resultRegionValue=Math.min.apply(null, resultJD)+","+Math.max.apply(null, resultWD)+"+"+Math.max.apply(null, resultJD)+","+Math.max.apply(null, resultWD)+"+"+Math.min.apply(null, resultJD)+","+Math.min.apply(null, resultWD)+"+"+Math.max.apply(null, resultJD)+","+Math.min.apply(null, resultWD); */
	       /*  var pt1 = new BMap.Point(Math.min.apply(null, resultJD),Math.min.apply(null, resultWD));//西南
	        var pt2= new BMap.Point(Math.max.apply(null, resultJD),Math.max.apply(null, resultWD));//东北 */
	        //resultPoint=[];
	        /* resultStation=[];
	      	getStationDetail(resultRegionValue);
	        for(var i = 0;i < markers.length; i++){
	        	var object2 = new Object();
	            object2.stationid=markers[i];
	            resultStation.push(object2);
	        } */
	    }
	    //多边形
	    if ( e.drawingMode == BMAP_DRAWING_POLYGON ) {
	        resultRegionType="4";
	        var jdwdArr=[];
	        resultRegionValue="";//清空
	        for(var i = 0; i < e.overlay.getPath().length; i++){
	             var object = new Object();
	             object.X= e.overlay.getPath()[i].lng;
	             object.Y= e.overlay.getPath()[i].lat;
	             jdwdArr.push(object);
	             resultRegionValue +=object.X+","+object.Y+"+";
	        }
	      	//getStationDetail(resultRegionValue);
	        /* var pts = [];
	        for(var j = 0; j < jdwdArr.length; j++){
	            var pt1 = new BMap.Point(jdwdArr[j].X, jdwdArr[j].Y);
	            pts.push(pt1);
	        }
	        var ply = new BMap.Polygon(pts); */
	        //resultPoint=[];
	        /* resultStation=[];
	        for(var i = 0;i < markers.length; i++){
	        	var object2 = new Object();
	            object2.stationid=markers[i];
	            resultStation.push(object2);
	        } */
	    }  
	     //开启编辑模式
			overlays[0].enableEditing();
		    	//添加事件监听函数
		    	if(resultRegionType=='3' || resultRegionType=='4'){
		    		overlays[0].addEventListener("lineupdate",function(e){
						resultRegionValue="";
						var path = overlays[0].getPath();//获取第一个多边形
						  for(var i=0;i<path.length;i++){
					 		var object = new Object();
					             object.X= path[i].lng;
					             object.Y= path[i].lat;
					             resultRegionValue +=object.X+","+object.Y+"+";
						  }
					}); 
		    	}else if(resultRegionType=='2'){
					overlays[0].addEventListener("lineupdate",function(e){
					    var radius = overlays[0].getRadius();//获取圆半径（单位米，可利用BMapLib.DistanceTool工具自定义单位）
					    var center = overlays[0].getCenter();//获取圆心坐标
					    resultRegionValue=center.lng+","+center.lat+"+"+radius;
					});
		    	}
			
	};
	//点在矩形内  西南脚点 东北脚点
	function ptInRect(pt,pt1,pt2){    
	    var bds = new BMap.Bounds(pt1, pt2); //测试Bounds对象
	    var result = BMapLib.GeoUtils.isPointInRect(pt, bds);
	    return result;
	}
	//点在圆内  测试点 圆心 半径
	function ptInCircle(pt,c,radius){
	    var circle = new BMap.Circle(c, radius);//测试圆
	    var result = BMapLib.GeoUtils.isPointInCircle(pt, circle);
	    return result;
	}
	
	var styleOptions = {
	    strokeColor:"blue",    //边线颜色。
	    fillColor:"blue",      //填充颜色。当参数为空时，圆形将没有填充效果。
	    strokeWeight: 3,       //边线的宽度，以像素为单位。
	    strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
	    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
	    strokeStyle: 'solid' //边线的样式，solid或dashed。
	}
	//实例化鼠标绘制工具
	var drawingManager = new BMapLib.DrawingManager(map, {
	    isOpen: false, //是否开启绘制模式
	    enableDrawingTool: true, //是否显示工具栏
	    drawingToolOptions: {
	        anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
	        offset: new BMap.Size(105, 10), //偏离值
	        drawingModes : [
	            BMAP_DRAWING_CIRCLE,
	            BMAP_DRAWING_POLYGON,
	            BMAP_DRAWING_RECTANGLE
	        ]
	    },
	    circleOptions: styleOptions, //圆的样式
	    polygonOptions: styleOptions, //多边形的样式
	    rectangleOptions: styleOptions //矩形的样式
	});  
	//添加鼠标绘制工具监听事件，用于获取绘制结果
	drawingManager.addEventListener('overlaycomplete', overlaycomplete);
	//drawingManager.setTop('true');
	function clearAll() {
	    for(var i = 0; i < overlays.length; i++){
	        map.removeOverlay(overlays[i]);
	    }
	    overlays.length = 0 ;
	}

}

var markers = [];//全省基站点
var cityJW ;
var isHaveJW="";//获取是否已有圈画过的图形，如有则定位到图形
var regionName;
var cityId="";
var heatMapLimit;
$(document).ready(function() {
	getHeatMapLimit();
    cityId=getUrlParam("cityId");
    resultRegionType=getUrlParam("resultRegionType");
    resultRegionValue=getUrlParam("regionTypeValue");
    cityJW= getJWByCityId(cityId);//获取对应地市大大致经纬度
    isHaveJW = getJWIsHave(resultRegionValue);
    getRegionName();
    initialFunc();
    getTuxing();
    //getData();
});
function getHeatMapLimit(){
	var url="/smsArea/findHeatMapLevel";
	    $.ajax({
	        url:url,
	        type:"post",
	        success:function(data){
	           if(data!=0){
	           	  heatMapLimit=data;
	           }else{
	           	  layer.msg("获取基站热力图展示极限级别失败，无法展示热力图");
	           }
	        },
                    error: function (data) {
                        layer.msg('系统异常，请联系管理员处理!');
                    }
	    });
}
//获取图形
function getTuxing(){
	if(resultRegionType==4||resultRegionType==3){
	    var arr = resultRegionValue.split('+');
	    if(arr.length>0){
		    var pts = [];
		    for(var i=0;i<arr.length;i++){
		        var pt = new BMap.Point(arr[i].split(',')[0], arr[i].split(',')[1]);
		    	pts.push(pt);
		    }
		    var styleOptions = {
			    strokeColor:"blue",    //边线颜色。
			    fillColor:"blue",      //填充颜色。当参数为空时，圆形将没有填充效果。
			    strokeWeight: 3,       //边线的宽度，以像素为单位。
			    strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
			    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
			    strokeStyle: 'solid' //边线的样式，solid或dashed。
			}
		    var ply = new BMap.Polygon(pts,styleOptions);
		    overlays.push(ply);
		    overlays[0].enableEditing();
		    map.addOverlay(ply);  
		    overlays[0].addEventListener("lineupdate",function(e){
				resultRegionValue="";
				var path = overlays[0].getPath();//获取第一个多边形
				  for(var i=0;i<path.length;i++){
			 		var object = new Object();
			             object.X= path[i].lng;
			             object.Y= path[i].lat;
			             resultRegionValue +=object.X+","+object.Y+"+";
				  }
			}); 
	    }
	}else if(resultRegionType==2){
		var arr = resultRegionValue.split('+');
	    if(arr.length==2){
	    	var center = arr[0];
	    	var radius = arr[1];
	    	var styleOptions = {
			    strokeColor:"blue",    //边线颜色。
			    fillColor:"blue",      //填充颜色。当参数为空时，圆形将没有填充效果。
			    strokeWeight: 3,       //边线的宽度，以像素为单位。
			    strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
			    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
			    strokeStyle: 'solid' //边线的样式，solid或dashed。
			}
			var pt = new BMap.Point(center.split(',')[0], center.split(',')[1]);
		    var cle = new BMap.Circle(pt,radius,styleOptions);
		    // alert(JSON.stringify(cle.getBounds()));
		    overlays.push(cle);
		    //overlays[0].enableEditing();
		    map.addOverlay(cle);
		    cle.enableEditing();
	    	overlays[0].addEventListener("lineupdate",function(event){
					    var radius = overlays[0].getRadius();//获取圆半径（单位米，可利用BMapLib.DistanceTool工具自定义单位）
					    var center = overlays[0].getCenter();//获取圆心坐标
					    resultRegionValue=center.lng+","+center.lat+"+"+radius;
					}); 
	    }
	}
}
//var t1 = window.setInterval(getData,1000); 
//获取区县名称
function getRegionName(){
	var url =decodeURI(decodeURI(location.search)); //获取url中"?"符后的字串，使用了两次decodeRUI解码
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
         var str = url.substr(1);
         strs = str.split("&");
         for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
         }
    }
    regionName = theRequest.regionName;
} 
//获取热力图
function getHeatMap(){
	if(map.getZoom()<heatMapLimit){
		flagheatmap='0';
		return false;
	}else{
		if(flagheatmap=='1'){
			getMapJW();
		}
	}
}
function getMapJW(){
	var list=new Array();
	var param1 = {};
	var param2 = {};
	var param3 = {};
	var param4 = {};
	var pt= map.getBounds();
    var sw=pt.getSouthWest();//西南
    var ne=pt.getNorthEast();//东北
    var wn = new BMap.Point(sw.lng, ne.lat);//获取西北角的经纬度(左上端点)
    var es = new BMap.Point(ne.lng, sw.lat);//获取东南角的经纬度(右下端点)
    
    param1.longitude = sw.lng;
    param1.latitude = sw.lat;
    list.push(param1);
   
    param2.longitude = wn.lng;
    param2.latitude = wn.lat;
    list.push(param2);
    
    param3.longitude = ne.lng;
    param3.latitude = ne.lat;
    list.push(param3);
	
	param4.longitude = es.lng;
    param4.latitude = es.lat;
    list.push(param4);
    
   	if(list.length==4){
	   	var params = {};
	    params.scopeData = list;
	    var jsonParams=JSON.stringify(params);
    	var url="/smsInterfaces/qryPersonFlows";
    	var index = layer.load(1, {shade: [0.1,'#fff'] });//0.1透明度的白色背景
	    $.ajax({
	    	contentType:"application/json;charset=UTF-8",
	    	method:"post",
	        url:url,
	        type:"post",
	        data:jsonParams,
	        dataType:'json',
	        success:function(data){
	           reliPoints = [];
	           if(data.length>0){
	           	  for(var i=0;i<data.length;i++){
	           	  		var pointJW = {};
	           	  		var m = data[i].longAndLat.split(",");
	           	  		if(m.length==2){
	           	  			pointJW.lng = m[0];
	           	  			pointJW.lat = m[1];
	           	  			pointJW.count = data[i].userNum;
	           	  			reliPoints.push(pointJW);
	           	  		}
	           	  }
	           	  console.time("HeatMap");
				  var points = reliPoints; 
				  if(!isSupportCanvas()){
			         alert('热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~')
			      }
				  heatmapOverlay = new BMapLib.HeatmapOverlay({"radius":15,"visible":true});
				  map.addOverlay(heatmapOverlay);
				  heatmapOverlay.setDataSet({data:points,max:500});
				  $("svg").css("z-index","300");//使圈画范围在热力图层之上
				  console.timeEnd("HeatMap");
				  layer.close(index);
	           }else{
	           	  layer.close(index);
	           	  layer.msg("获取基站经纬度和总用户量失败，无法展示热力图");
	           }
	        },
                    error: function (data) {
                    	layer.close(index);
                        layer.msg('系统异常，请联系管理员处理!');
                    }
	    });
    }
}
// 苏州   11淮安   12宿迁   13南京   14连云港   15徐州   16常州   17镇江   18无锡   19南通   20泰州   21 盐城   22 扬州   23
function getJWByCityId(cityId){
    if(cityId=="11"){
        return new BMap.Point(120.58,31.30);
    }else if(cityId=="12"){
        return new BMap.Point(119.02,33.62);
    }else if(cityId=="13"){
        return new BMap.Point(118.28,33.97);
    }else if(cityId=="14"){
        return new BMap.Point(118.78,32.04);
    }else if(cityId=="15"){
        return new BMap.Point(119.22,34.60);
    }else if(cityId=="16"){
        return new BMap.Point(117.18,34.27);
    }else if(cityId=="17"){
        return new BMap.Point(119.95,31.78);
    }else if(cityId=="18"){
        return new BMap.Point(119.45,32.20);
    }else if(cityId=="19"){
        return new BMap.Point(120.30,31.57);
    }else if(cityId=="20"){
        return new BMap.Point(120.88,31.98);
    }else if(cityId=="21"){
        return new BMap.Point(119.92,32.45);
    }else if(cityId=="22"){
        return new BMap.Point(120.15,33.35);
    }else if(cityId=="23"){
        return new BMap.Point(119.40,32.40);
    }else if(cityId=="25"){
    	return new BMap.Point(118.78,32.04);
    }else{
        return new BMap.Point(118.78,32.04);
    }
}

function getJWIsHave(resultRegionValue){
	var array = resultRegionValue.split('+');
	if(array.length>2){
		var JW = array[0].split(',');
		var JD = JW[0];
		var WD = JW[1];
		return new BMap.Point(JD,WD);
	}else{
		return "";
	}
	
}

function getData(){
	markers=[];
    var pt= map.getBounds();
    var sw=pt.getSouthWest();//西南
    var ne=pt.getNorthEast();//东北
    var lng1=sw.lng;
    var lng2=ne.lng;
    var lat1=sw.lat;
    var lat2=ne.lat;
    if(map.getZoom()>11){
	    var url="/smsArea/findAllStation?cityId="+getUrlParam("cityId")+"&countyId=&longitudeMin="+lng1+"&longitudeMax="+lng2+"&latitudeMin="+lat1+"&latitudeMax="+lat2;
	    $.ajax({
	        url:url,
	        type:"post",
	        success:function(data){
	            $.each(data,function(i,d){
	                markers[i]={position:{lat:d.latitude,lng:d.longitude},stationid:d.stationMarkId,stationname:d.stationMarkName};
	            });
	        }
	    });
    }
}
//插入基站信息表
function mapSave(){
    //window.clearInterval(t1); 
	if(resultRegionType=="4"||resultRegionType=="3"||resultRegionType=="2"){
	    resultRegionValue=resultRegionValue.substring(0,resultRegionValue.length-1);
	}
	
	var mgrId=getUrlParam("mgrId");
	if(mgrId==""){
	    window.wxc.xcConfirm("未获取项目ID，请先创建项目", window.wxc.xcConfirm.typeEnum.info);
	    return false;
	}
	/* if(map.getZoom()<=14){
        window.wxc.xcConfirm("当前地图基站过多，请缩放后再画区域", window.wxc.xcConfirm.typeEnum.info);
        return false;
    } */
    
    if(resultRegionType=="2"||resultRegionType=="3"||resultRegionType=="4"){
	    getStationDetail(resultRegionValue);
    }
     /* if(resultRegionType=="3"||resultRegionType=="4"){
	    //getStationDetail(resultRegionValue);
	    getJWTest2();
    }else if(resultRegionType=="2"){
    	getJWTest();
    }  */
}

function getJWTest2(){
		var array = resultRegionValue.split('+');
		var list=new Array();
		for(var i=0;i<array.length;i++){
			var param1 = {};
			var JW = array[i].split(',');
			var JD = JW[0];
			var WD = JW[1];
			param1.longitude = JD;
	    	param1.latitude = WD;
	    	list.push(param1);
		}
		var params = {};
	    params.scopeData = list;
	    var jsonParams=JSON.stringify(params);
    	var url="/smsInterfaces/qryPersonFlows";
    	var index = layer.load(1, {shade: [0.1,'#fff'] });//0.1透明度的白色背景
	    $.ajax({
	    	contentType:"application/json;charset=UTF-8",
	    	method:"post",
	        url:url,
	        type:"post",
	        data:jsonParams,
	        dataType:'json',
	        success:function(data){
	           console.time("HeatMap");
	           if(data.length>0){
	              var points = [];  // 添加海量点数据
	           	  for(var i=0;i<data.length;i++){
	           	  		var m = data[i].longAndLat.split(",");
	           	  		if(m.length==2){
	           	  			points.push(new BMap.Point(m[0], m[1]));
	           	  		}
	           	  }
	           	  var options = {
				            size: BMAP_POINT_SIZE_SMALL,
				            shape: BMAP_POINT_SHAPE_STAR,
				            color: '#d340c3'
				        }
				  var pointCollection = new BMap.PointCollection(points, options);  // 初始化PointCollection
				  pointCollection.addEventListener('click', function (e) {
				          alert('单击点的坐标为：' + e.point.lng + ',' + e.point.lat);  // 监听点击事件
				        });
				  map.addOverlay(pointCollection);  // 添加Overlay
				  console.timeEnd("HeatMap");
				  layer.close(index);
	           }else{
	           	  layer.close(index);
	           	  layer.msg("获取基站经纬度和总用户量失败，无法展示海量点");
	           }
	        },
                    error: function (data) {
                    	layer.close(index);
                        layer.msg('系统异常，请联系管理员处理!');
                    }
	    });
}

function getJWTest(){
		var array = resultRegionValue.split('+');
		var JW = array[0].split(',');
		var JD = JW[0];
		var WD = JW[1];
		var list=new Array();
		var param1 = {};
		param1.longitude = JD;
	    param1.latitude = WD;
	    list.push(param1);
		var params = {};
	    params.scopeData = list;
	    params.radius = array[1];
	    var jsonParams=JSON.stringify(params);
    	var url="/smsInterfaces/qryPersonFlows";
    	var index = layer.load(1, {shade: [0.1,'#fff'] });//0.1透明度的白色背景
	    $.ajax({
	    	contentType:"application/json;charset=UTF-8",
	    	method:"post",
	        url:url,
	        type:"post",
	        data:jsonParams,
	        dataType:'json',
	        success:function(data){
	           console.time("HeatMap");
	           if(data.length>0){
	              var points = [];  // 添加海量点数据
	           	  for(var i=0;i<data.length;i++){
	           	  		var m = data[i].longAndLat.split(",");
	           	  		if(m.length==2){
	           	  			points.push(new BMap.Point(m[0], m[1]));
	           	  		}
	           	  }
	           	  var options = {
				            size: BMAP_POINT_SIZE_SMALL,
				            shape: BMAP_POINT_SHAPE_STAR,
				            color: '#d340c3'
				        }
				  var pointCollection = new BMap.PointCollection(points, options);  // 初始化PointCollection
				  pointCollection.addEventListener('click', function (e) {
				          alert('单击点的坐标为：' + e.point.lng + ',' + e.point.lat);  // 监听点击事件
				        });
				  map.addOverlay(pointCollection);  // 添加Overlay
				  console.timeEnd("HeatMap");
				  layer.close(index);
	           }else{
	           	  layer.close(index);
	           	  layer.msg("获取基站经纬度和总用户量失败，无法展示海量点");
	           }
	        },
                    error: function (data) {
                    	layer.close(index);
                        layer.msg('系统异常，请联系管理员处理!');
                    }
	    });
}

function jumpToFisrt(mgrid,regionid,type,detail){
    //parent.ChooseValues(type,detail);
    parent.$('#xiangmuid').val(mgrid);
    parent.$('#quyuid').val(regionid);
    parent.$('#quyutype').val(type);
    parent.$('#quyudetail').val(detail);
    parent.$('#xiangmuvalue').html("已选取");
    parent.$('#sendLimitVal').val(resultStation);
    //parent.$('#ditubtn').attr("style","background-color:#ccc");
    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    parent.layer.close(index); //再执行关闭
    
}

//设置点Icon nouse
function addMapOverlay(){
    for(var index = 0; index < markers.length; index++ ){
        var point = new BMap.Point(markers[index].position.lng,markers[index].position.lat);
        var marker = new BMap.Marker(point,{icon:new BMap.Icon("http://api.map.baidu.com/lbsapi/createmap/images/icon.png",new BMap.Size(20,25)
    )});
    marker.setLabel();//不显示地理名称      
    map.addOverlay(marker);
  };
}

//调用接口获取圈画范围内的基站
   	function getStationDetail(resultRegionValue){
   		var cityId=getUrlParam("cityId");
   		var mgrId=getUrlParam("mgrId");
   		var sendStart=getUrlParam("sendStart");
   		var sendEnd=getUrlParam("sendEnd");
   		var scopeType=getUrlParam("scopeType");
   		var countyId=getUrlParam("countyId");
   		var mgrState=getUrlParam("mgrState");
   		var checkState=getUrlParam("checkState");
   		var param2 = {
                    mgrId:mgrId,
                    sendStart: sendStart,   //项目开始时间
                    sendEnd: sendEnd,//结束时间
                    scopeType: scopeType,//发送范围类型
                    cityId: cityId,
                    countyId: countyId,
                    longAndLats: resultRegionValue,//经纬度集合
                    checkState: checkState,//0审核通过 ，1审核不通过，2未审核
                    mgrState: mgrState//0开启 ，1暂停， 2关闭
                };
        var jsonParams=JSON.stringify(param2);
        var index = layer.load(1, {shade: [0.1,'#fff'] });//0.1透明度的白色背景
        var url = "/smsInterfaces/sendMgrLimit";
        $.ajax({
             contentType:"application/json;charset=UTF-8",
             type: 'post',
			 data: jsonParams,
			 url: url,
			 dataType:'json',
			 success:function(data){
				 layer.close(index);
				 if(data.retCode==0){
					  stationCount = data.stationCount;
					  regionId = data.regionId;
				      // markers = data.stationIds.split(',')
				      // resultStation=[];
				      // for(var i = 0;i < markers.length; i++){
				      //   	var object2 = new Object();
				      //       object2.stationid=markers[i];
				      //       resultStation.push(object2);
				      // }
				      saveMapInfo();
				 }else{
				 	layer.msg('该区域下无基站,请重新选取');
				 }
			},error:function(){
				layer.close(index);
			    layer.msg('系统异常，请联系管理员处理!');
			}
       });                       		    	
   	}
function saveMapInfo(){
	if(stationCount==0){
        window.wxc.xcConfirm("该区域下无基站，请清除后重新画区域", window.wxc.xcConfirm.typeEnum.info);
        return false;
    }else{
    	var cityId=getUrlParam("cityId");
	   	var mgrId=getUrlParam("mgrId");
	   	var flag=getUrlParam("flag");
	    var param = {
	        cityId: cityId,
	        mgrId: mgrId,
	        resultRegionType:resultRegionType,
	        resultRegionValue:resultRegionValue,
			regionId:regionId
	        //resultStation:JSON.stringify(resultStation)
	    };
	    var jsonParams=JSON.stringify(param);
        //alert("jsonParams:"+jsonParams);
	    //$("#loadingDiv").show();
	    var index = layer.load(1, {shade: [0.1,'#fff'] });//0.1透明度的白色背景
	    var url="/smsArea/mapSave";
	    $.ajax({
	        url: url,
	        data: param,
	        type:"post",
	        success:function(obj){
	          //$("#loadingDiv").hide();
	          layer.close(index);
	             if (obj.code == 0) {
	                 var data=obj.data;
	                 if(stationCount>0){
		                var txt=  "成功保存发送区域,共"+stationCount+"个基站，点击确认按钮完成项目配置，点击取消按钮修改发送区域！";
						var option = {
							title: "提示",
							btn: parseInt("0011",2),//0001确认按钮    0011 确认取消
							onOk: function(){
								//jumpToFisrt(mgrId,data[2],data[3],data[4]);
								if(flag=="insert"){
									parent.parent.location.href="../index.html";
								}else{
									jumpToFisrt(mgrId,data[2],data[3],data[4]);
								}
							}
						}
						window.wxc.xcConfirm(txt, "custom", option);
	                }else{
	                    window.wxc.xcConfirm("保存发送区域失败，请重试", window.wxc.xcConfirm.typeEnum.error);
	                }
	            }
	        },error:function(){
	        	layer.close(index);
			    layer.msg('系统异常，请联系管理员处理!');
	        }
	    });
    }
}
	function openHeatmap(){
        heatmapOverlay.show();
    }
 
    function closeHeatmap(){
        heatmapOverlay.hide();
    }
    
    function OpenOrCloseHeatmap(){
    	  if(flagheatmap=="1"){
    	 	flagheatmap="0";
    	 	heatmapOverlay.toggle();
    	 	layer.msg('热力图已关闭!');
    	 }else{
    	 	flagheatmap="1";
    	 	getHeatMap();
    	 	layer.msg('开启热力图!');
    	 } 
    }
    //判断浏览区是否支持canvas
    function isSupportCanvas(){
        var elem = document.createElement('canvas');
        return !!(elem.getContext && elem.getContext('2d'));
    }
 
    function setGradient(){
        /*格式如下所示:
        {
            0:'rgb(102, 255, 0)',
            .5:'rgb(255, 170, 0)',
            1:'rgb(255, 0, 0)'
        }*/
        var gradient = {};
        var colors = document.querySelectorAll("input[type='color']");
        colors = [].slice.call(colors,0);
        colors.forEach(function(ele){
            gradient[ele.getAttribute("data-key")] = ele.value;
        });
        heatmapOverlay.setOptions({"gradient":gradient});
    }
});
</script>
